package net.kazed.nextaction.context.activity;

import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import net.kazed.nextaction.R;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;

/**
 * Display list of contexts.
 */
public class ContextsActivity extends ListActivity {

   public static final String SELECTED_ITEM = "SELECTED_ITEM";
   
   private static final int INSERT_ID = Menu.FIRST;

	private static final String cTag = "ContextsActivity";
	private static final int NEW_ITEM = 1;
   private static final int EDIT_ITEM = 2;
	
   private Long mItemIdToSelect = null;
   private SparseIntArray mTaskCountArray;

   /**
    * Cursor to select for list of items
    */
   protected Cursor cursor;

   @Override
   public void onCreate(Bundle icicle) {
      super.onCreate(icicle);
      setContentView(getContentViewResId());
      setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
      // If no data was given in the intent (because we were started
      // as a MAIN activity), then use our default content provider.
      Intent intent = getIntent();
      if (intent.getData() == null) {
         intent.setData(getContentUri());
      }
      cursor = managedQuery(GtdContext.CONTENT_URI, GtdContext.FULL_PROJECTION.getFieldNames(),
            null, null, 
            GtdContext.NAME + " ASC");
      setListAdapter(createListAdapter(cursor));

      animateList();
   }

   @Override
	protected void onResume() {
		super.onResume();
      if (mItemIdToSelect != null) {
         Log.d(cTag, "New item id = " + mItemIdToSelect);
         // see if list contains the new item
         int count = getItemCount();
         CursorAdapter adapter = (CursorAdapter) getListAdapter();
         for (int i = 0; i < count; i++) {
            long currentItemId = adapter.getItemId(i);
            Log.d(cTag, "Current id=" + currentItemId + " pos=" + i);
            if (currentItemId == mItemIdToSelect) {
               Log.d(cTag, "Found new item - selecting");
               setSelection(i);
               break;
            }
         }
         mItemIdToSelect = null;
      }
		Cursor cursor = getContentResolver().query(GtdContext.cContextTasksContentURI, GtdContext.cFullTaskProjection, null, null, null);
		mTaskCountArray = new SparseIntArray();
      while (cursor.moveToNext()) {
         mTaskCountArray.put(cursor.getInt(0), cursor.getInt(1));
      }
		cursor.close();
	}
	
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      String menuName = getResources().getString(R.string.menu_add_context);
      MenuItem item = menu.add(0, INSERT_ID, 0, menuName).setIcon(R.drawable.list_add);
      item.setAlphabeticShortcut('a');
      return super.onCreateOptionsMenu(menu);
   }
   
   @Override
   protected void onListItemClick(ListView l, View v, int position, long id) {
      Uri itemUri = ContentUris.withAppendedId(getContentUri(), id);

      String action = getIntent().getAction();
      if (Intent.ACTION_PICK.equals(action)
            || Intent.ACTION_GET_CONTENT.equals(action)) {
         // The caller is waiting for us to return a task selected by
         // the user. They have clicked on one, so return it now.
         Bundle bundle = new Bundle();
          bundle.putString(SELECTED_ITEM, itemUri.toString());
          Intent intent = new Intent();
          intent.putExtras(bundle);
          setResult(RESULT_OK, intent);        
      } else {
         // Launch activity to view/edit the currently selected item
         Intent intent = new Intent();
         Bundle bundle = new Bundle();
         bundle.putString(SELECTED_ITEM, itemUri.toString());
         intent.putExtras(bundle);
         intent.setData(itemUri);
         intent.setAction(Intent.ACTION_VIEW);
         startActivityForResult(intent, EDIT_ITEM);
      }
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      case INSERT_ID:
         Uri uri = ContentUris.withAppendedId(GtdContext.CONTENT_ITEM_URI, 0);
         Intent intent = new Intent(this, ContextEditorActivity.class); // new Intent(Intent.ACTION_INSERT, uri);
         intent.setData(GtdContext.CONTENT_URI);
         intent.setAction(Intent.ACTION_INSERT);
         startActivityForResult(intent, NEW_ITEM);
         break;
      }
      return super.onOptionsItemSelected(item);
   }
   
   @Override
   protected void onActivityResult(int requestCode, int resultCode,
         Intent data) {
      switch (requestCode) {
      case NEW_ITEM:
         if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
               Uri uri = Uri.parse(data.getStringExtra(SELECTED_ITEM));
               mItemIdToSelect = ContentUris.parseId(uri);
               // need to do the actual checking and selecting
               // in onResume, otherwise getItemId(i) is always 0
               // and setSelection(i) does nothing
            }
         }
         break;
      default:
         Log.e(cTag, "Unknown requestCode: " + requestCode);
      break;
      }
   }

   protected void animateList() {
      AnimationSet set = new AnimationSet(true);

      Animation animation = new AlphaAnimation(0.0f, 1.0f);
      animation.setDuration(50);
      set.addAnimation(animation);

      animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
      animation.setDuration(100);
      set.addAnimation(animation);

      LayoutAnimationController controller = new LayoutAnimationController(
            set, 0.5f);
      ListView listView = getListView();
      listView.setLayoutAnimation(controller);
   }
   
   /**
    * @return Number of items in the list.
    */
   protected final int getItemCount() {
      return cursor.getCount();
   }

	protected int getContentViewResId() {
		return R.layout.contexts;
	}

	protected Uri getContentUri() {
		return GtdContext.CONTENT_URI;
	}
	
	protected Uri getChildContentUri() {
		return Task.CONTENT_URI;
	}
	
	String getChildName() {
		return getString(R.string.task_name);
	}
	
	protected void deleteChildren(int groupId) {
		getContentResolver().delete(getChildContentUri(), Task.CONTEXT_ID + " = ?", new String[] {String.valueOf(groupId)});
	}

	protected ListAdapter createListAdapter(Cursor cursor) {
		ListAdapter adapter =
				new SimpleCursorAdapter(this,
						android.R.layout.simple_list_item_1, cursor,
						new String[] { GtdContext.NAME },
						new int[] { android.R.id.text1 }) {
			
			public View getView(int position, View convertView, ViewGroup parent) {
			   Cursor cursor = (Cursor) getItem(position);
			   GtdContext context = readGtdContext(cursor);

				ContextView contextView;
				if (convertView instanceof ContextView) {
					contextView = (ContextView) convertView;
				} else {
					contextView = new ContextView(parent.getContext());
				}
				contextView.setTaskCountArray(mTaskCountArray);
				boolean isSelected = false;
				contextView.updateView(context, isSelected);
				return contextView;
			}


		};
		return adapter;
	}
	
   private GtdContext readGtdContext(Cursor cursor) {
      GtdContext context = new GtdContext(cursor);
      return context;
   }

	protected int getSelectedItemChildCount() {
		final long groupId = getSelectedItemId();
		return mTaskCountArray.get((int)groupId);
	}
	
    /**
     * Return the intent generated when a list item is clicked.
     * 
     * @param url type of data selected
     */ 
    protected Intent getClickIntent(Uri uri) {
    	// if a context is clicked on, show context view.
    	Intent intent = new Intent(this, ContextViewActivity.class);
    	intent.setData(uri);
    	return intent;
    }
	
    protected GtdContext readItem(Cursor c) {
        return readGtdContext(c);
    }

     /**
      * Permanently delete the selected item.
      */
     protected void deleteItem() {
       int childCount = getSelectedItemChildCount();
       if (childCount > 0) {
          final int groupId = (int)getSelectedItemId();
          OnClickListener buttonListener = new OnClickListener() {
             public void onClick(DialogInterface dialog, int which) {
                if (which == DialogInterface.BUTTON2) {
                   Log.i(cTag, "Deleting group id " + groupId);
                   deleteChildren(groupId);
                } else {
                   Log.d(cTag, "Hit Cancel button. Do nothing.");
                }
             }
          };
       }
     }

    protected boolean supportsViewAction() {
       return false;
    }


}